<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

$db = Database::getInstance();

// 获取系统所有设置
$settings = [];
$settingsResult = $db->fetchAll("SELECT * FROM " . DB_PREFIX . "settings ORDER BY category, setting_key");

// 将设置整理为类别分组
$settingsByCategory = [];
foreach ($settingsResult as $setting) {
    $category = $setting['category'];
    if (!isset($settingsByCategory[$category])) {
        $settingsByCategory[$category] = [];
    }
    $settingsByCategory[$category][] = $setting;
    $settings[$setting['setting_key']] = $setting['setting_value'];
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $updatedSettings = $_POST['settings'] ?? [];
    $errors = [];
    
    // 验证和保存设置
    foreach ($updatedSettings as $key => $value) {
        // 获取当前设置信息
        $settingInfo = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "settings WHERE setting_key = ?", [$key]);
        
        if ($settingInfo) {
            // 根据设置类型进行验证
            $isValid = true;
            $validationMessage = '';
            
            switch ($settingInfo['type']) {
                case 'number':
                    if (!is_numeric($value)) {
                        $isValid = false;
                        $validationMessage = '必须是数字';
                    } elseif (isset($settingInfo['min_value']) && $value < $settingInfo['min_value']) {
                        $isValid = false;
                        $validationMessage = '不能小于 ' . $settingInfo['min_value'];
                    } elseif (isset($settingInfo['max_value']) && $value > $settingInfo['max_value']) {
                        $isValid = false;
                        $validationMessage = '不能大于 ' . $settingInfo['max_value'];
                    }
                    break;
                    
                case 'boolean':
                    // 布尔值通常是复选框，未选中时可能不会提交，所以要处理
                    $value = isset($value) && $value ? '1' : '0';
                    break;
                    
                case 'email':
                    if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                        $isValid = false;
                        $validationMessage = '不是有效的电子邮件地址';
                    }
                    break;
                    
                case 'url':
                    if (!empty($value) && !filter_var($value, FILTER_VALIDATE_URL)) {
                        $isValid = false;
                        $validationMessage = '不是有效的URL';
                    }
                    break;
            }
            
            if ($isValid) {
                // 更新设置
                $db->update('settings', ['setting_value' => $value], 'setting_key = ?', [$key]);
                $settings[$key] = $value; // 更新本地变量，用于表单显示
            } else {
                $errors[$key] = $settingInfo['display_name'] . ' ' . $validationMessage;
            }
        }
    }
    
    // 处理文件上传
    if (isset($_FILES['site_logo']) && $_FILES['site_logo']['size'] > 0) {
        $result = uploadImage('site_logo', '../uploads/system/');
        
        if ($result['success']) {
            // 删除旧logo（如果存在）
            $oldLogo = $settings['site_logo'] ?? '';
            if (!empty($oldLogo) && file_exists('../' . $oldLogo)) {
                @unlink('../' . $oldLogo);
            }
            
            // 更新logo设置
            $db->update('settings', ['setting_value' => $result['path']], 'setting_key = ?', ['site_logo']);
            $settings['site_logo'] = $result['path'];
        } else {
            $errors['site_logo'] = '上传网站LOGO失败: ' . $result['message'];
        }
    }
    
    // 处理网站图标上传
    if (isset($_FILES['site_favicon']) && $_FILES['site_favicon']['size'] > 0) {
        $allowedExtensions = ['ico', 'png'];
        $maxSize = 1 * 1024 * 1024; // 1MB
        
        $result = uploadFile('site_favicon', '../', $allowedExtensions, $maxSize);
        
        if ($result['success']) {
            // 删除旧图标（如果存在）
            $oldFavicon = $settings['site_favicon'] ?? '';
            if (!empty($oldFavicon) && file_exists('../' . $oldFavicon)) {
                @unlink('../' . $oldFavicon);
            }
            
            // 更新图标设置
            $db->update('settings', ['setting_value' => $result['path']], 'setting_key = ?', ['site_favicon']);
            $settings['site_favicon'] = $result['path'];
        } else {
            $errors['site_favicon'] = '上传网站图标失败: ' . $result['message'];
        }
    }
    
    // 设置消息提示
    if (empty($errors)) {
        $_SESSION['flash_message'] = '系统设置已成功更新';
        $_SESSION['flash_type'] = 'success';
        
        // 重定向以防止重复提交
        header('Location: settings.php');
        exit;
    } else {
        $_SESSION['flash_message'] = '保存设置时出现错误，请检查下面的错误提示';
        $_SESSION['flash_type'] = 'danger';
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-gear"></i> 系统设置</h1>
</div>

<form action="" method="post" enctype="multipart/form-data">
    <!-- 设置选项卡 -->
    <div class="card mb-4">
        <div class="card-header">
            <ul class="nav nav-tabs card-header-tabs" id="settingsTabs" role="tablist">
                <?php $firstCategory = true; ?>
                <?php foreach ($settingsByCategory as $category => $categorySettings): ?>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link <?php echo $firstCategory ? 'active' : ''; ?>" 
                                id="<?php echo $category; ?>-tab" 
                                data-bs-toggle="tab" 
                                data-bs-target="#<?php echo $category; ?>" 
                                type="button" 
                                role="tab" 
                                aria-controls="<?php echo $category; ?>" 
                                aria-selected="<?php echo $firstCategory ? 'true' : 'false'; ?>">
                            <?php 
                            // 根据类别显示合适的图标和名称
                            $icons = [
                                'general' => 'bi-gear',
                                'website' => 'bi-globe',
                                'mail' => 'bi-envelope',
                                'game' => 'bi-controller',
                                'social' => 'bi-people',
                                'security' => 'bi-shield-lock',
                                'api' => 'bi-code-slash'
                            ];
                            
                            $categoryNames = [
                                'general' => '常规设置',
                                'website' => '网站设置',
                                'mail' => '邮件设置',
                                'game' => '游戏设置',
                                'social' => '社交设置',
                                'security' => '安全设置',
                                'api' => 'API设置'
                            ];
                            
                            $icon = isset($icons[$category]) ? $icons[$category] : 'bi-three-dots';
                            $categoryName = isset($categoryNames[$category]) ? $categoryNames[$category] : ucfirst($category);
                            
                            echo '<i class="bi ' . $icon . '"></i> ' . $categoryName;
                            ?>
                        </button>
                    </li>
                    <?php $firstCategory = false; ?>
                <?php endforeach; ?>
            </ul>
        </div>
        <div class="card-body">
            <div class="tab-content" id="settingsTabContent">
                <?php $firstCategory = true; ?>
                <?php foreach ($settingsByCategory as $category => $categorySettings): ?>
                    <div class="tab-pane fade <?php echo $firstCategory ? 'show active' : ''; ?>" 
                         id="<?php echo $category; ?>" 
                         role="tabpanel" 
                         aria-labelledby="<?php echo $category; ?>-tab">
                        
                        <div class="row g-3">
                            <?php foreach ($categorySettings as $setting): ?>
                                <div class="col-md-6 mb-3">
                                    <label for="<?php echo $setting['setting_key']; ?>" class="form-label">
                                        <?php echo htmlspecialchars($setting['display_name']); ?>
                                        <?php if ($setting['is_required']): ?>
                                            <span class="text-danger">*</span>
                                        <?php endif; ?>
                                    </label>
                                    
                                    <?php 
                                    // 根据设置类型显示不同的输入控件
                                    $value = $settings[$setting['setting_key']] ?? '';
                                    $isInvalid = isset($errors[$setting['setting_key']]);
                                    
                                    switch ($setting['type']):
                                        case 'text': 
                                        case 'email':
                                        case 'url':
                                    ?>
                                        <input type="<?php echo $setting['type']; ?>" 
                                               class="form-control <?php echo $isInvalid ? 'is-invalid' : ''; ?>" 
                                               id="<?php echo $setting['setting_key']; ?>" 
                                               name="settings[<?php echo $setting['setting_key']; ?>]" 
                                               value="<?php echo htmlspecialchars($value); ?>"
                                               <?php echo $setting['is_required'] ? 'required' : ''; ?>>
                                    <?php break; case 'textarea': ?>
                                        <textarea class="form-control <?php echo $isInvalid ? 'is-invalid' : ''; ?>" 
                                                  id="<?php echo $setting['setting_key']; ?>" 
                                                  name="settings[<?php echo $setting['setting_key']; ?>]" 
                                                  rows="3"
                                                  <?php echo $setting['is_required'] ? 'required' : ''; ?>><?php echo htmlspecialchars($value); ?></textarea>
                                    <?php break; case 'number': ?>
                                        <input type="number" 
                                               class="form-control <?php echo $isInvalid ? 'is-invalid' : ''; ?>" 
                                               id="<?php echo $setting['setting_key']; ?>" 
                                               name="settings[<?php echo $setting['setting_key']; ?>]" 
                                               value="<?php echo htmlspecialchars($value); ?>"
                                               <?php if (isset($setting['min_value'])): ?>min="<?php echo $setting['min_value']; ?>"<?php endif; ?>
                                               <?php if (isset($setting['max_value'])): ?>max="<?php echo $setting['max_value']; ?>"<?php endif; ?>
                                               <?php echo $setting['is_required'] ? 'required' : ''; ?>>
                                    <?php break; case 'boolean': ?>
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" 
                                                   type="checkbox" 
                                                   id="<?php echo $setting['setting_key']; ?>" 
                                                   name="settings[<?php echo $setting['setting_key']; ?>]" 
                                                   value="1"
                                                   <?php echo $value == '1' ? 'checked' : ''; ?>>
                                        </div>
                                    <?php break; case 'select': 
                                        $options = json_decode($setting['options'], true) ?: [];
                                    ?>
                                        <select class="form-select <?php echo $isInvalid ? 'is-invalid' : ''; ?>" 
                                                id="<?php echo $setting['setting_key']; ?>" 
                                                name="settings[<?php echo $setting['setting_key']; ?>]"
                                                <?php echo $setting['is_required'] ? 'required' : ''; ?>>
                                            <?php foreach ($options as $optionValue => $optionLabel): ?>
                                                <option value="<?php echo htmlspecialchars($optionValue); ?>" 
                                                        <?php echo $value == $optionValue ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($optionLabel); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    <?php break; case 'file': 
                                        // 特殊处理网站logo和图标
                                        if ($setting['setting_key'] === 'site_logo'):
                                    ?>
                                        <input type="file" 
                                               class="form-control <?php echo $isInvalid ? 'is-invalid' : ''; ?>" 
                                               id="site_logo" 
                                               name="site_logo" 
                                               accept="image/*">
                                        <?php if (!empty($value)): ?>
                                            <div class="mt-2">
                                                <img src="<?php echo htmlspecialchars($value); ?>" alt="当前LOGO" class="img-thumbnail" style="max-height: 50px;">
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($setting['setting_key'] === 'site_favicon'): ?>
                                        <input type="file" 
                                               class="form-control <?php echo $isInvalid ? 'is-invalid' : ''; ?>" 
                                               id="site_favicon" 
                                               name="site_favicon" 
                                               accept=".ico,.png">
                                        <?php if (!empty($value)): ?>
                                            <div class="mt-2">
                                                <img src="<?php echo htmlspecialchars($value); ?>" alt="当前图标" class="img-thumbnail" style="max-height: 32px;">
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    <?php break; endswitch; ?>
                                    
                                    <?php if ($isInvalid): ?>
                                        <div class="invalid-feedback"><?php echo $errors[$setting['setting_key']]; ?></div>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($setting['description'])): ?>
                                        <div class="form-text"><?php echo htmlspecialchars($setting['description']); ?></div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php $firstCategory = false; ?>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="card-footer">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-save"></i> 保存设置
            </button>
            <button type="reset" class="btn btn-secondary ms-2">
                <i class="bi bi-arrow-counterclockwise"></i> 重置
            </button>
        </div>
    </div>
</form>

<!-- 缓存控制 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-speedometer"></i> 系统维护
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-6 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title">缓存管理</h5>
                        <p class="card-text">清除系统缓存可以解决一些显示异常的问题，但可能会暂时影响系统性能。</p>
                        <a href="maintenance.php?action=clear_cache" class="btn btn-warning" 
                           onclick="return confirm('确定要清除所有缓存吗？这可能会暂时影响系统性能。')">
                            <i class="bi bi-trash"></i> 清除所有缓存
                        </a>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title">数据库优化</h5>
                        <p class="card-text">优化数据库可以提升系统性能，建议在系统负载较低时执行。</p>
                        <a href="maintenance.php?action=optimize_db" class="btn btn-info" 
                           onclick="return confirm('确定要优化数据库吗？此过程可能需要一些时间。')">
                            <i class="bi bi-lightning-charge"></i> 优化数据库
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
require_once 'includes/footer.php';
?> 